import React, { Component } from 'react';
import { Button, Form, Input, Space, Row, Col, Timeline, TreeSelect } from "antd";
import GoBack from "@/components/TheGoBack";
import TheUpload from "@/components/TheUpload";
import TheQuill from "@/components/TheQuill";
import { knowledgeAdd, knowledgeEdit, knowledgeView, getOperationLog, knowledgeClassifyTree } from '@/request/petCircleUtil/knowledge';
export default class Comments extends Component {
  constructor() {
    super()
    this.quillRef = React.createRef
    this.state = {
      knowledgeId: '', //知识库内容id
      btnLoading: false, // 按钮loading
      classifyList: [], //知识类目列表
      textLength: 0, // 富文本字数提示
      knowledgeText: '', //富文本内容
      operationLogData: [], //操作日志数据
      knowledgeClassifyList: [], // 知识类目
      knowledgeClassifyValue: '', // 类目值
      knowledgeClassifyTitle: '', // 类目名称
    }
  }
  async componentDidMount() {
    const { id } = this.props.match.params
    if (id != 0) { await this.getData(id) }
    await this.getClassifyList()
    await this.operationLog()
  }
  // 知识库内容详情
  getData = async (knowledgeId) => {
    let res = await knowledgeView({ knowledgeId })
    if (res.code === 0) {
      this.formRef.setFieldsValue({ ...res.data, })
      this.setState({
        fileList: [
          {
            uid: '-1',
            name: 'image.png',
            url: res.data.knowledgeImage,
          },
        ],
        knowledgeId: res.data.knowledgeId
      })
      this.setNewsContent(res.data.knowledgeText)
      this.quillRef.upData(res.data.knowledgeText)
    }
  };
  // 知识类目列表
  getClassifyList = async () => {
    let res = await knowledgeClassifyTree()
    if (res.code === 0 && res.data) {
      this.setState({
        knowledgeClassifyList: res.data.map(item => {
          return {
            value: item.knowledgeClassifyId,
            title: item.name,
            disabled: true,
            children: item.childrenList ? item.childrenList.map(v => {
              return {
                value: v.knowledgeClassifyId,
                title: v.name,
              }
            }) : []
          }
        })
      })
    }
  }
  // 照片上传
  getFileResult = (value) => {
    if (value.length && value[0] && value[0].response) {
      this.formRef.setFieldsValue({ knowledgeImage: value[0].response.data });
    } else {
      this.formRef.setFieldsValue({ knowledgeImage: '', })
    }
  };
  // 富文本内容
  setNewsContent = (data, length) => {
    if (this.formRef != null) {
      this.formRef.setFieldsValue({ knowledgeText: data })
    }
    this.setState({
      textLength: length,
    })
  }
  // 确定新建/编辑表单
  onFinish = async (values) => {
    this.setState({ btnLoading: true })
    if (values.knowledgeText === '<p></p>') {
      React.$message({ type: 'error', content: '文章内容不能为空' })
    } else {
      if (this.state.knowledgeId == 0) {
        let res = await knowledgeAdd({ ...values, })
        if (res.code === 0) {
          React.$message({ type: 'info', content: '新建成功' })
          this.props.history.goBack()
        }
      } else {
        let res = await knowledgeEdit({ ...values, knowledgeId: this.state.knowledgeId })
        if (res.code === 0) {
          React.$message({ type: 'info', content: '修改成功' })
          this.props.history.goBack()
        }
      }
    }
    this.setState({ btnLoading: false })
  }
  // 查看操作日志
  operationLog = async () => {
    let res = await getOperationLog({ dataType: 3, dataId: this.state.knowledgeId ? this.state.knowledgeId : '0' })
    if (res.code === 0) {
      this.setState({ operationLogData: res.data })
    }
  }
  // 树结构
  onChange = (value, label) => {
    this.setState({ knowledgeClassifyValue: value })
  }
  render() {
    const { knowledgeId, btnLoading, fileList, knowledgeText, textLength, knowledgeClassifyList, operationLogData, knowledgeClassifyValue } = this.state
    return (
      <Row style={{ overflow: 'hidden' }}>
        <Col span={knowledgeId === '' ? 24 : 18}>
          <div className='p-layout-box' style={{ height: '90vh' }}>
            <GoBack history={this.props.history} title={knowledgeId == 0 ? "新增知识库内容" : "修改知识库内容"} />
            <Form onFinish={this.onFinish}
              style={{ overflowY: 'scroll' }}
              ref={ref => this.formRef = ref}
              labelCol={{ span: 2 }}
              wrapperCol={{ span: 16, }}
            >
              <p style={{ margin: '10px 0' }}>文章信息</p>
              <Form.Item rules={[{ required: true, message: '请上传文章头图' }]} label="文章头图" name="knowledgeImage">
                <TheUpload getFileResult={(value) => this.getFileResult(value)} maxSize={20} fileList={fileList} len={1} />
              </Form.Item>
              <Form.Item rules={[{ required: true }]} label="文章标题" name="knowledgeTitle">
                <Input style={{ width: '500px' }} placeholder="请输入文章标题" maxLength={20} />
              </Form.Item>
              <Form.Item label="分享副标题" name="knowledgeSubTitle" tooltip="此副标题不会在APP展示，只用于分享展示；未填时分享卡片小标题默认为：你想了解的宠物知识， 都在哈奇马养宠小百科~">
                <Input style={{ width: '500px' }} placeholder="请输入30字以内的分享副标题" maxLength={30} />
              </Form.Item>
              <Form.Item rules={[{ required: true }]} label="文章内容" name="knowledgeText"
                extra={`${textLength}/8000`}
              >
                <TheQuill ref={(ref) => this.quillRef = ref} defaultValue={knowledgeText} setNewsContent={this.setNewsContent} maxTextLength={8000} />
              </Form.Item>
              <Form.Item rules={[{ required: true, message: '请选择知识类目' }]} label="知识类目" name="knowledgeClassifyId">
                <TreeSelect
                  value={knowledgeClassifyValue}
                  placeholder="请选择知识库类目"
                  allowClear
                  onChange={this.onChange}
                  treeData={knowledgeClassifyList}
                />
              </Form.Item>
              <div style={{ marginBottom: '20px' }}>其他信息</div>
              <Form.Item label="备注" name="remarks">
                <Input style={{ width: '500px' }} placeholder="请输入备注" />
              </Form.Item>
              <Form.Item
                wrapperCol={{
                  offset: 16,
                  span: 14,
                }}
              >
                <Space>
                  <Button loading={btnLoading} htmlType="submit" type="primary">保存</Button>
                  <Button onClick={() => this.props.history.goBack()}>取消</Button>
                </Space>
              </Form.Item>
            </Form>
          </div >
        </Col>
        {
          knowledgeId !== '' && <Col span={6}>
            <div className=' p-layout-box' style={{ marginLeft: '20px', height: '90vh' }}>
              <p style={{ marginBottom: '20px' }}>操作日志</p>
              <Timeline >
                {operationLogData.map(item => {
                  return <Timeline.Item color="gray">
                    <div>{item.info}</div>
                    <div style={{ display: 'flex', color: '#999999' }}>
                      <div style={{ marginRight: '10px' }}>{item.operationUserName}</div>
                      <div>{item.operationTime}</div>
                    </div>
                  </Timeline.Item>
                })}
              </Timeline>
            </div>
          </Col>
        }

      </Row>
    );
  }
}